<template>
  <div>
    <div>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="分配权限">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
              @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="form.checkedPerms" @change="handleCheckedPermsChange">
              <el-checkbox v-for="item in perms" :label="item.id" :key="item.id">{{ item.permissionName }}</el-checkbox>
            </el-checkbox-group>
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="onSubmit(form)">确定</el-button>
            <el-button @click="handlecancer">取消</el-button>
          </el-form-item>
        </el-form>
    </div>
  </div>
</template>

<script>
import { getPermList, setPermByroleId } from '@/api/api'
export default {
  data () {
    return {
      role: JSON.parse(this.$route.query.role),
      checkAll: false,
      form: {
        checkedPerms: []
      },
      checkedPermsIdandName: [],
      perms: [],
      isIndeterminate: true
    }
  },
  methods: {
    handleCheckAllChange (val) {
      this.form.checkedPerms = val ? this.perms : []
      this.isIndeterminate = false
    },
    handleCheckedPermsChange (value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.perms.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.perms.length
    },
    onSubmit (form) {
      // console.log(this.role.roleId, form.checkedPerms)
      const params = {
        roleId: this.role.roleId,
        permList: form.checkedPerms
      }
      setPermByroleId(params).then(res => {
        // console.log(res.data)
        this.$router.back()
      })
    },
    handlecancer () {
      this.$router.back()
    }
  },
  mounted () {
    getPermList().then(res => {
      // console.log(res.data)
      this.perms = res.data.data
    })
    getPermList(this.role.roleId).then(res => {
      console.log(res.data)
      this.checkedPermsIdandName = res.data.data
      for (let i = 0; i < this.checkedPermsIdandName.length; i++) {
        this.form.checkedPerms.push(this.checkedPermsIdandName[i].id)
      }
    })
  }
}
</script>
